import logging

from aiogram import types
from aiogram_dialog import DialogManager
from arq import ArqRedis
from fluentogram import TranslatorRunner

from src.application.order.service import OrderService
from src.application.order.service.proxy_service import ProxyService
from src.infrastructure.db.services.categories import get_category_by_name

logger = logging.getLogger(__name__)


async def set_proxy_provider(call: types.CallbackQuery, _, manager: DialogManager, provider_id: str):
    order_service: OrderService = manager.middleware_data.get("order_service")
    proxy_service: ProxyService = manager.middleware_data.get("proxy_service")
    arqredis: ArqRedis = manager.middleware_data.get("arqredis")
    locale: TranslatorRunner = manager.middleware_data.get("locale")
    country_id: int = manager.dialog_data.get("country_id")

    category = await get_category_by_name(db_session, "Подписка")
    subscription_order = await order_service.get_user_subscription(call.from_user.id)
    manager.dialog_data["order_id"] = subscription_order.id

    proxies = await proxy_service.get_available_proxies(
        proxy_type="mobile",
        proxy_privacy="private",
        country_id=country_id,
        provider_id=int(provider_id),
        category_id=category.id,
        tg_user_id=call.from_user.id,
        limit=1,
    )

    if proxies.total <= 0:
        await call.message.answer(locale.get("no-subscription-proxies"))
        return

    if len(subscription_order.proxies) > 0:
        proxy_id = subscription_order.proxies[0].id
    else:
        proxy_id = None

    new_proxy_id = proxies.proxies[0].id

    try:
        await arqredis.enqueue_job(
            "change_proxy",
            locale=locale,
            user_id=call.from_user.id,
            order_id=subscription_order.id,
            proxy_id=proxy_id,
            new_proxy_id=new_proxy_id,
            country_id=country_id,
            provider_id=provider_id,
        )

        logger.info(f"Добавлена задача по смене прокси в заказе №{subscription_order.id}")

        await arqredis.enqueue_job(
            "check_proxy_speed_job",
            locale=locale,
            user_id=call.from_user.id,
            new_proxy_id=new_proxy_id,
        )
        logger.info(f"Добавлена задача по проверке скорости прокси №{new_proxy_id}")

        await call.message.answer(locale.get("in-work-msg"))
    except Exception as e:
        logger.exception(e)
        await call.message.answer(locale.get("error-msg"))
    await manager.done()
